package com.android.vending.billing;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.stek.utils.SharePreferenceUtils;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;

public class BillingHelper extends ContextWrapper {
	// =================================================================================================

	public static String BINDING_ACTION = "com.android.vending.billing.InAppBillingService.BIND";
	private static final String ORDER_ID = "orderId";
	public static int REQUEST_KEY = 10;

	public static int STATE_UNKNOWN = -1;
	public static int STATE_NON_PURCHASED = 0;
	public static int STATE_PURCHASED = 1;

	public static boolean isAwesome(Context context, String sku) {
		return isPurcharsed(context, sku);
	}

	public static boolean isPurcharsed(Context context, String sku) {
		return getPurchaseState(context, sku) == STATE_PURCHASED;
		// return true;
	}

	public static int getPurchaseState(Context context, String sku) {
		return SharePreferenceUtils.getPrefInt(context, sku,
				STATE_NON_PURCHASED);
	}

	public static String getPurchaseId(Context context, String sku) {
		return SharePreferenceUtils.getPrefString(context, sku + ORDER_ID, "");
	}

	public static void recheckPurchase(final Context context,
			String productType, String sku) {
		recheckPurchase(context, null, productType, sku);
	}

	public static void recheckPurchase(final Context context,
			final Runnable callback, final String productType, final String sku) {
		final ServiceConnection serviceConn = new ServiceConnection() {
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				IInAppBillingService _service = IInAppBillingService.Stub
						.asInterface(service);

				Bundle ownedItems;
				try {
					ownedItems = _service.getPurchases(3,
							context.getPackageName(), productType, null);
					int response = ownedItems.getInt("RESPONSE_CODE");

					if (response == 0) {
						// SharePreferenceUtils.clearValue(context, sku);
						// SharePreferenceUtils.clearValue(context, sku +
						// ORDER_ID);
						ArrayList<String> ownedSkus = ownedItems
								.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
						// ownedSkus.add(getPurchaseSKU(context));
						ArrayList<String> purchaseDataList = ownedItems
								.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
						for (int i = 0; i < ownedSkus.size(); ++i) {
							updateCachePurchasePreference(context,
									ownedSkus.get(i), STATE_PURCHASED);
							JSONObject data = new JSONObject(
									purchaseDataList.get(i));
							updateCachePurchaseIdPreference(context,
									ownedSkus.get(i), data.getString(ORDER_ID));

						}
					}

					if (callback != null) {
						callback.run();
					}

					context.unbindService(this);
				} catch (Throwable e) {
					e.printStackTrace();
					return;
				}

			}

			@Override
			public void onServiceDisconnected(ComponentName name) {
			}
		};

		try {
			context.bindService(new Intent(BINDING_ACTION), serviceConn,
					Context.BIND_AUTO_CREATE);
		} catch (Exception ex) {
			if (callback != null) {
				callback.run();
			}
		}
	}

	private static void updateCachePurchasePreference(Context context,
			String sku, int state) {
		SharePreferenceUtils.putPrefInt(context, sku, state);
	}

	private static void updateCachePurchaseIdPreference(Context context,
			String sku, String id) {
		SharePreferenceUtils.putPrefString(context, sku + ORDER_ID, id);
	}

	// =================================================================================================

	public final static String INAPP = "inapp";
	public final static String SUBS = "subs";
	private IInAppBillingService mService;
	private boolean mIsConnected = false;

	private final ServiceConnection mServiceConn = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mService = null;
			mIsConnected = false;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mService = IInAppBillingService.Stub.asInterface(service);
			mIsConnected = true;
		}
	};

	// =================================================================================================

	public BillingHelper(Context base) {
		super(base);
	}

	public boolean isConnected() {
		return this.mIsConnected;
	}

	public void connect() {
		this.bindService(new Intent(BINDING_ACTION), this.mServiceConn,
				Context.BIND_AUTO_CREATE);
	}

	public void release() {
		if (this.mIsConnected) {
			this.unbindService(this.mServiceConn);
		}
	}

	// TODO toast error message
	public int buy(String productType, String sku, Activity caller,
			int requestKey) {
		if (mService == null) {
			return -1;
		}
		try {
			Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(),
					sku, productType, sku);

			int responseCode = buyIntentBundle.getInt("RESPONSE_CODE");
			PendingIntent pendingIntent = buyIntentBundle
					.getParcelable("BUY_INTENT");
			if (pendingIntent != null
					&& pendingIntent.getIntentSender() != null) {
				caller.startIntentSenderForResult(
						pendingIntent.getIntentSender(), requestKey,
						new Intent(), Integer.valueOf(0), Integer.valueOf(0),
						Integer.valueOf(0));
			}

			// if (responseCode == 7) {
			// updateCachePurchasePreference(caller, sku, STATE_PURCHASED);
			// }

			return responseCode;
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (SendIntentException e) {
			e.printStackTrace();
		}

		return -2;
	}

	// TODO toast error message
	public boolean processPurchaseResult(Intent intent) {
		// int responseCode = intent.getIntExtra("RESPONSE_CODE", 0);
		// String dataSignature = intent.getStringExtra("INAPP_DATA_SIGNATURE");
		String purchaseData = intent.getStringExtra("INAPP_PURCHASE_DATA");

		try {
			JSONObject jo = new JSONObject(purchaseData);
			String sku = jo.getString("productId");
			updateCachePurchasePreference(this, sku, STATE_PURCHASED);
			return true;
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}
	}

	// =================================================================================================
}